/*
 * @description:
 * @version: 1.0.1
 * @Author: xuqiulin
 * @Date: 2021-04-30 11:08:50
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-04-30 15:26:19
 */
package controllers

import (
	"io"
	"os"
	"strconv"

	"path/filepath"

	"github.com/gin-gonic/gin"

	"GameServer/Common/data"
	"GameServer/conf"
)

func RefreshConf(c *gin.Context) {
	err := data.Init(conf.Conf.DataDir)
	if err != nil {
		handleErr(c, err.Error())
		return
	}
	handleOk(c, nil)

}

// @Summary 服务器配置表信息
// @Produce  json
// @Param table path string true "table"
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /config/data/{table} [get]
func TableAllData(c *gin.Context) {
	table := c.Param("table")

	r, ok := data.GetAllDatas(table)
	if !ok {
		handleErr(c, "没有数据")
		return
	}

	handleOk(c, r)
}

// @Summary 服务器配置表信息 by key
// @Produce  json
// @Param table path string true "table"
// @Param key path string true "key"
// @Success 200 {string} json "{"code":0,"data":{},"msg":"ok"}"
// @Router /config/data/{table}/{key} [get]
func TableSigleData(c *gin.Context) {
	table := c.Param("table")
	key := c.Param("key")
	key1, _ := strconv.ParseUint(key, 10, 64)

	r, ok := data.Get(table, key1)
	if !ok {
		handleErr(c, "没有数据")
		return
	}
	handleOk(c, r)
}

func UploadConf(c *gin.Context) {
	c.Request.ParseMultipartForm(1024 * 1024 * 1024 * 2)
	multiPartform, _ := c.MultipartForm()
	for _, files := range multiPartform.File {
		for _, file := range files {
			out, err := os.Create(filepath.Join(conf.Conf.DataDir, file.Filename))
			if err != nil {
				handleErr(c, err.Error())
				return
			}
			f, err := file.Open()
			if err != nil {
				handleErr(c, err.Error())
				return
			}
			io.Copy(out, f)
			out.Close()
		}
	}
	err := data.Init(conf.Conf.DataDir)
	if err != nil {
		handleErr(c, err.Error())
		return
	}
	handleOk(c, nil)
}
